package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.Timeline;
import com.innovation.chengzhangriji.TimelineAudioUrl;
import com.innovation.chengzhangriji.TimelineLastServerTime;
import com.innovation.chengzhangriji.TimelinePhoto;
import com.innovation.chengzhangriji.TimelinePhotoUrl;
import com.innovation.chengzhangriji.TimelineVideoScreenshotUrl;
import com.innovation.chengzhangriji.TimelineVideoUrl;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.TypeDataResponse;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.service.SyncTimelineService;
import com.innovation.chengzhangriji.ui.model.UITimeline;
import com.innovation.chengzhangriji.ui.model.UITimelineAudio;
import com.innovation.chengzhangriji.ui.model.UITimelineMilestone;
import com.innovation.chengzhangriji.ui.model.UITimelinePhoto;
import com.innovation.chengzhangriji.ui.model.UITimelineText;
import com.innovation.chengzhangriji.ui.model.UITimelineVideo;
import com.innovation.chengzhangriji.ui.widget.MainToolbar;
import com.innovation.chengzhangriji.ui.widget.MultiSwipeRefreshLayout;
import com.innovation.chengzhangriji.ui.widget.TimeLineBarView;
import com.innovation.chengzhangriji.ui.widget.TimelineAdapter;
import com.innovation.chengzhangriji.util.FileUtils;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

public class TimelineFragment extends BaseFragment implements TimeLineBarView.SendMessageListener, TimeLineBarView.ExecuteListener, MainToolbar.OnClickActionListener, SwipeRefreshLayout.OnRefreshListener, TimeLineBarView.RecordListener, View.OnTouchListener {

    private MainToolbar mToolbar;

    private ImageView mPoint;

    private ImageView imageMsgPoint;

    private MultiSwipeRefreshLayout mSwipeRefreshLayout;

    private RecyclerView mRecyclerView;

    private TimelineAdapter mAdapter;

    private TimeLineBarView timeLineBarView;

    private ProgressBar mProgressBar;

    private SlideUpListener mListener;

    private String role;

    private Baby mBaby;

    private SyncBroadcastReceiver mReceiver;

    private String url;
    private String name;
    private String day;
    private boolean show;
    private boolean hasNewMsg;

    int height;

    // 上拉开始标志位
    private boolean mSlideUpStart;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.REQUEST_OPEN_BABY_INFO && resultCode == Activity.RESULT_OK) {
            LoginInfo loginInfo = Config.getLoginInfo(getActivity());
            if (loginInfo == null) {
                return;
            }
            String userId = loginInfo.getUserID();
            int babyID = loginInfo.getBabyID();
            if (babyID == LoginInfo.EMPTY_BABY_ID) {
                return;
            }
            Baby baby = DatabaseManager.getInstance(getActivity()).queryBaby(userId, babyID);
            ((TimelineActivity) getActivity()).setMenuHead(baby.getImageUrl(), baby.getName());
            setBabyHead(baby.getImageUrl());
            setNoteName(baby.getName());
            setBabyDay(getBabyDay(baby, baby.getState(), System.currentTimeMillis()));
            update();
        } else if (requestCode == Config.REQUEST_OPEN_TIMELINE_PHOTO || requestCode == Config.REQUEST_OPEN_TIMELINE_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                UITimelinePhoto photo = new UITimelinePhoto();
                String uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
                long localTime = System.currentTimeMillis();
                String date = getDateToString(localTime);
                int state = mBaby.getState();
                String count = getCount(state, localTime);
                String time = getTimeToString(localTime);
                setBaseData(photo, uuid, localTime, date, count, time, role);

                Bundle bundle = data.getExtras();
                String theme = bundle.getString("theme");
                String text = bundle.getString("text");
                String[] localUrls = bundle.getStringArray("urls");
                photo.setText(text);
                photo.setTheme(theme);
                photo.setLength(localUrls.length);
                photo.setUrls(null);
                photo.setLocalThumbUrls(localUrls);
                mAdapter.addPhoto(photo);

                int length = localUrls.length;
                String[] newUrls = new String[length];
                for (int i = 0; i < localUrls.length; i++) {
                    File file = Config.createFile(getActivity(), Config.PHOTO_DIR);
                    File source = new File(localUrls[i]);
                    try {
                        FileUtils.copyFileUsingFileChannels(source, file);
                        newUrls[i] = file.getPath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // 对图片进行压缩


                insertPhoto(Config.getLoginInfo(getActivity()), localTime, uuid, text, theme, newUrls, state);
                Config.startUploadTimelineService(getActivity());
            }
        } else if (requestCode == Config.REQUEST_OPEN_TIMELINE_VIDEO) {
            if (resultCode == Activity.RESULT_OK) {
                UITimelineVideo video = new UITimelineVideo();
                String uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
                long localTime = System.currentTimeMillis();
                String date = getDateToString(localTime);
                int state = mBaby.getState();
                String count = getCount(state, localTime);
                String time = getTimeToString(localTime);
                setBaseData(video, uuid, localTime, date, count, time, role);

                Bundle bundle = data.getExtras();
                String screenshotUrl = bundle.getString("screenshotUrl");
                int length = bundle.getInt("length");
                String localUrl = bundle.getString("localUrl");
                video.setLocalScreenshotUrl(screenshotUrl);
                mAdapter.addVideo(video);
                insertVideo(Config.getLoginInfo(getActivity()), localTime, uuid, screenshotUrl, length, localUrl, state);
                Config.startUploadTimelineService(getActivity());
            }
        } else if (requestCode == Config.REQUEST_OPEN_TIMELINE_MILESTONE) {
            if (resultCode == Activity.RESULT_OK) {
                UITimelineMilestone milestone = new UITimelineMilestone();
                String uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
                long localTime = System.currentTimeMillis();
                String date = getDateToString(localTime);
                int state = mBaby.getState();
                String count = getCount(state, localTime);
                String time = getTimeToString(localTime);
                setBaseData(milestone, uuid, localTime, date, count, time, role);


                Bundle bundle = data.getExtras();
                int id = bundle.getInt("milestoneID");
                String text = bundle.getString("milestone");
                milestone.setMilestoneID(id);
                milestone.setMilestone(text);

                mAdapter.addMilestone(milestone);
                insertMilestone(Config.getLoginInfo(getActivity()), localTime, uuid, id, text, state);
                Config.startUploadTimelineService(getActivity());
            }
        }
    }

    LinearLayoutManager layoutManager;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_timeline, container, false);

        mToolbar = (MainToolbar) view.findViewById(R.id.toolbar);
        mToolbar.setOnClickActionListener(this);
        mToolbar.setBabyHead(url);
        mToolbar.setBabyName(name);
        mToolbar.setBabyDay(day);
        mPoint = (ImageView) view.findViewById(R.id.image_point);
        if (show) {
            mPoint.setVisibility(View.VISIBLE);
        } else {
            mPoint.setVisibility(View.INVISIBLE);
        }

        imageMsgPoint = (ImageView) view.findViewById(R.id.image_point_msg);
        hasNewMsg = Config.getHasNewMessage(getActivity().getApplicationContext()) || Config.getHasNewComment(getActivity().getApplicationContext());
        if (hasNewMsg) {
            imageMsgPoint.setVisibility(View.VISIBLE);
        } else {
            imageMsgPoint.setVisibility(View.INVISIBLE);
        }

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        timeLineBarView = (TimeLineBarView) view.findViewById(R.id.timeline_bar);
        timeLineBarView.setSendMessageListener(this);
        timeLineBarView.setExecuteListener(this);
        timeLineBarView.setRecordListener(this);
        mAdapter = new TimelineAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemAnimator(null);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mRecyclerView.getLayoutParams();
        lp.setMargins(0, 0, 0, height);
        mRecyclerView.setLayoutParams(lp);
        mRecyclerView.setOnTouchListener(this);

        mSwipeRefreshLayout = (MultiSwipeRefreshLayout) view.findViewById(R.id.swipe);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeRefreshLayout.setSwipeableChildren(R.id.recycler_view);

        mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);

        mListener = new SlideUpListener();
        mRecyclerView.setOnScrollListener(mListener);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        queryBaby(Config.getLoginInfo(getActivity()));
        queryTimeline(Config.getLoginInfo(getActivity()), Config.QUERY_LENGTH);
        registerReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 取消语音
        mAdapter.stopPlayback();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_TIMELINE);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_TIMELINE);
    }

    @Override
    public void onClickActionMenu() {
        if (getActivity() instanceof TimelineActivity) {
            ((TimelineActivity) getActivity()).openDrawer();
        }
    }

    @Override
    public void onClickNote() {
        Intent intent = new Intent(getActivity(), BabyActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_BABY_INFO);
    }

    @Override
    public void onClickActionDiscover() {
        Config.setHasNewMessage(getActivity(), false);
        setVisibilityPointMsg(false);
        Intent intent = new Intent(getActivity(), DiscoverActivity.class);
        startActivity(intent);
    }

    @Override
    public void sendMessage(String text) {
        // 插入数据到数据库
        // 后台自动准备提交
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        UITimelineText uiText = new UITimelineText();
        long localTime = System.currentTimeMillis();
        String date = getDateToString(localTime);
        int state = mBaby.getState();
        String count = getCount(state, localTime);
        String time = getTimeToString(localTime);
        setBaseData(uiText, uuid, localTime, date, count, time, role);
        uiText.setText(text);
        mAdapter.addText(uiText);
        insertText(Config.getLoginInfo(getActivity()), localTime, uuid, text, state);
        Config.startUploadTimelineService(getActivity());
        mRecyclerView.scrollToPosition(0);
        // 隐藏输入法
        InputMethodManager methodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        methodManager.hideSoftInputFromWindow(mRecyclerView.getWindowToken(), 0);
    }

    @Override
    public void execute(int position) {
        Intent intent;
        switch (position) {
            case Config.FUNCTION_PHOTO:
                intent = new Intent(getActivity(), TimelinePhotoActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_PHOTO);
                break;
            case Config.FUNCTION_CAMERA:
                intent = new Intent(getActivity(), TimelineCameraActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_CAMERA);
                break;
            case Config.FUNCTION_VIDEO:
                intent = new Intent(getActivity(), TimelineVideoActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_VIDEO);
                return;
            case Config.FUNCTION_FIRST:
                intent = new Intent(getActivity(), TimelineMilestoneActivity.class);
                startActivityForResult(intent, Config.REQUEST_OPEN_TIMELINE_MILESTONE);
                break;
        }
        timeLineBarView.close();
        mRecyclerView.scrollToPosition(0);
    }

    @Override
    public void success(int length, String path) {
        UITimelineAudio audio = new UITimelineAudio();
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        long createTS = System.currentTimeMillis();
        String date = getDateToString(createTS);
        int state = mBaby.getState();
        String count = getCount(state, createTS);
        String time = getTimeToString(createTS);
        setBaseData(audio, uuid, createTS, date, count, time, role);

        audio.setLength(length);
        audio.setLocalUrl(path);
        mAdapter.addAudio(audio);
        insertAudio(Config.getLoginInfo(getActivity()), createTS, uuid, length, path, state);
        Config.startUploadTimelineService(getActivity());
        mRecyclerView.scrollToPosition(0);
    }

    @Override
    public void start() {
    }

    // TODO 临时
    private static final String SPACE = " ";

    @Override
    public void timing(int length) {
        tipShow(SPACE + SPACE + SPACE + "录音中" + SPACE + length + SPACE + SPACE + '\n' + "(上滑可以取消)");
    }

    @Override
    public void failure() {
        tipShow("录音失败");
    }

    @Override
    public void cancel() {
        tipShow("录音取消");
    }

    @Override
    public void onRefresh() {
        mAdapter.stopPlayback();
        Intent intent = new Intent(getActivity(), SyncTimelineService.class);
        getActivity().startService(intent);
    }

    public void setBabyHead(String url) {
        this.url = url;
    }

    public void setNoteName(String name) {
        this.name = name;
    }

    public void setBabyDay(String day) {
        this.day = day;
    }

    public void setVisibilityPoint(boolean show) {
        this.show = show;
        if (mPoint == null) {
            return;
        }
        if (show) {
            mPoint.setVisibility(View.VISIBLE);
        } else {
            mPoint.setVisibility(View.INVISIBLE);
        }
    }

    public void setVisibilityPointMsg(boolean hasNewMsg) {
        this.hasNewMsg = hasNewMsg;
        if (imageMsgPoint == null) {
            return;
        }
        if (hasNewMsg) {
            imageMsgPoint.setVisibility(View.VISIBLE);
        } else {
            imageMsgPoint.setVisibility(View.INVISIBLE);
        }
    }

    public void update() {
        mToolbar.setBabyHead(url);
        mToolbar.setBabyName(name);
        mToolbar.setBabyDay(day);
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo != null) {
            mAdapter.clear();
            queryBaby(Config.getLoginInfo(getActivity()));
            queryTimeline(Config.getLoginInfo(getActivity()), Config.QUERY_LENGTH);
        }
    }

    private void queryBaby(LoginInfo login) {
        final String userId = login.getUserID();
        final int babyID = login.getBabyID();
        Baby baby = DatabaseManager.getInstance(getActivity()).queryBaby(userId, babyID);
        mBaby = baby;
        role = baby.getParentName();
        BabyAndParent babyAndParent = DatabaseManager.getInstance(getActivity()).queryBabyAndParent(userId, babyID);
        if (babyAndParent == null) {
            return;
        }
        int permission = babyAndParent.getPermission();
        if (permission == 0) {
            timeLineBarView.setVisibility(View.INVISIBLE);
            height = 0;
        } else {
            height = getResources().getDimensionPixelSize(R.dimen.base_height);
        }
    }

    private void queryTimeline(LoginInfo login, int number) {
        final int babyID = login.getBabyID();
        updateTimeline(DatabaseManager.getInstance(getActivity()).queryTimeline(babyID, number));
    }

    private void updateTimeline(List<Timeline> timelineList) {
        int length = timelineList.size();
        for (int i = 0; i < length; i++) {
            String uuid = timelineList.get(i).getUuid();
            long localTime = timelineList.get(i).getCreateTS();
            String date = getDateToString(localTime);
            String time = getTimeToString(localTime);
            int state = timelineList.get(i).getState();
            String count = getCount(state, localTime);
            String role = timelineList.get(i).getRole();
            switch (timelineList.get(i).getType()) {
                case TypeDataResponse.TYPE_TEXT:
                    Logger.d("增加文字");
                    UITimelineText text = new UITimelineText();
                    setBaseData(text, uuid, localTime, date, count, time, role);
                    text.setText(DatabaseManager.getInstance(getActivity()).queryTimelineText(uuid).getText());
                    mAdapter.addTextDesc(text);
                    break;
                case TypeDataResponse.TYPE_PHOTO:
                    Logger.d("增加图片");
                    UITimelinePhoto photo = new UITimelinePhoto();
                    setBaseData(photo, uuid, localTime, date, count, time, role);
                    TimelinePhoto timelinePhoto = DatabaseManager.getInstance(getActivity()).queryTimelinePhoto(uuid);
                    photo.setText(timelinePhoto.getText());
                    photo.setTheme(timelinePhoto.getTheme());
                    TimelinePhotoUrl[] timelinePhotoUrls = DatabaseManager.getInstance(getActivity()).queryTimelinePhotoUrls(uuid);
                    int urlCount = timelinePhotoUrls.length;
                    photo.setLength(urlCount);
                    String[] urls = new String[urlCount];
                    String[] localThumbUrls = new String[urlCount];
                    for (int j = 0; j < urlCount; j++) {
                        urls[j] = timelinePhotoUrls[j].getUrl();
                        localThumbUrls[j] = timelinePhotoUrls[j].getLocalThumbUrl();
                    }
                    photo.setUrls(urls);
                    photo.setLocalThumbUrls(localThumbUrls);
                    mAdapter.addPhotoDesc(photo);
                    break;
                case TypeDataResponse.TYPE_AUDIO:
                    Logger.d("增加音频");
                    UITimelineAudio audio = new UITimelineAudio();
                    setBaseData(audio, uuid, localTime, date, count, time, role);
                    TimelineAudioUrl timelineAudioUrl = DatabaseManager.getInstance(getActivity()).queryTimelineAudioUrl(uuid);
                    audio.setLength(timelineAudioUrl.getLength());
                    audio.setLocalUrl(timelineAudioUrl.getLocalUrl());
                    mAdapter.addAudioDesc(audio);
                    break;
                case TypeDataResponse.TYPE_VIDEO:
                    Logger.d("增加视频");
                    UITimelineVideo video = new UITimelineVideo();
                    setBaseData(video, uuid, localTime, date, count, time, role);
                    TimelineVideoUrl timelineVideoUrl = DatabaseManager.getInstance(getActivity()).queryTimelineVideoUrl(uuid);
                    TimelineVideoScreenshotUrl timelineVideoScreenshotUrl = DatabaseManager.getInstance(getActivity()).queryTimelineVideoScreenshotUrl(uuid);
                    video.setUrl(timelineVideoUrl.getUrl());
                    video.setLocalScreenshotUrl(timelineVideoScreenshotUrl.getLocalUrl());
                    video.setIsProgress(false);
                    video.setProgress(0);
                    mAdapter.addVideoDesc(video);
                    break;
                case TypeDataResponse.TYPE_MILESTONE:
                    Logger.d("增加里程碑");
                    UITimelineMilestone milestone = new UITimelineMilestone();
                    setBaseData(milestone, uuid, localTime, date, count, time, role);
                    milestone.setMilestone(DatabaseManager.getInstance(getActivity()).queryTimelineMilestone(uuid).getMilestone());
                    mAdapter.addMilestoneDesc(milestone);
                    break;
            }
        }
    }

    private void updateTimeline(String uuid, String url, String localUrl) {
        if (!TextUtils.isEmpty(localUrl)) {
            mAdapter.updateComplete(uuid, url, localUrl);
        }
    }

    private void insertText(LoginInfo login, long localTime, String uuid, String text, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(getActivity()).insertTimelineText(uuid, babyID, userID, role, state, localTime, text);
    }

    private void insertPhoto(LoginInfo login, long localTime, String uuid, String text, String theme, String[] localUrls, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(getActivity()).insertTimelinePhoto(uuid, babyID, userID, role, state, localTime, text, theme, localUrls);
    }

    private void insertAudio(LoginInfo login, long createTS, String uuid, int length, String localUrl, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(getActivity()).insertTimelineAudio(uuid, babyID, userID, role, state, createTS, length, localUrl);
    }

    private void insertVideo(LoginInfo login, long createTS, String uuid, String screenshotUrl, int length, String localUrl, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(getActivity()).insertTimelineVideo(uuid, babyID, userID, role, state, createTS, screenshotUrl, length, localUrl);
    }

    private void insertMilestone(LoginInfo login, long localTime, String uuid, int milestoneID, String milestone, int state) {
        final int babyID = login.getBabyID();
        final String userID = login.getUserID();
        DatabaseManager.getInstance(getActivity()).insertTimelineMilestone(uuid, babyID, userID, role, state, localTime, milestoneID, milestone);
    }

    private void setBaseData(UITimeline base, String uuid, long localTime, String date, String count, String time, String role) {
        base.setUuid(uuid);
        base.setLocalTime(localTime);
        base.setDate(date);
        base.setCount(count);
        base.setTime(time);
        base.setRole(role);
    }

    private String getDateToString(long time) {
        DateTime dateTime = new DateTime(time);
        dateTime = new DateTime(dateTime.year().get(), dateTime.monthOfYear().get(), dateTime.dayOfMonth().get(), 0, 0);
        DateTime today = new DateTime(System.currentTimeMillis());
        Period d = new Period(dateTime, today, PeriodType.days());
        if (d.getDays() == 0) {
            return "今天";
        } else if (d.getDays() == 1) {
            return "昨天";
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(time);
        return sf.format(date);
    }

    private String getTimeToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(time);
        return sf.format(date);
    }

    private String getCount(int state, long time) {
        return getBabyDay(mBaby, state, time);
    }

    private String getBabyDay(Baby baby, int state, long time) {
        switch (state) {
            case Client.STATE_READY:
                return "备孕中";
            case Client.STATE_START:
                if (baby.getDueDate() != 0) {
                    return getBabyDayByDueDateOrLastDate(baby.getDueDate() - 280 * 24 * 60 * 60 * 1000l, time);
                } else {
                    return getBabyDayByDueDateOrLastDate(baby.getLastDate(), time);
                }
            case Client.STATE_END:
                return getBabyDayByBirthday(baby.getBirthday(), time);
        }
        return null;
    }

    private String getBabyDayByDueDateOrLastDate(long time, long time2) {
        DateTime startTime = new DateTime(time);
        DateTime endTime = new DateTime(time2);
        Period pWeek = new Period(startTime, endTime, PeriodType.weeks());
        String week = "";
        String day = "";
        if (pWeek.getWeeks() != 0) {
            week = pWeek.getWeeks() + "周";
        }
        Period pDay = new Period(startTime, endTime, PeriodType.yearWeekDay());
        if (pDay.getDays() != 0) {
            day = pDay.getDays() + "天";
        }
        if (TextUtils.isEmpty(week) && TextUtils.isEmpty(day)) {
            return "孕1天";
        }
        return "孕" + week + day;
    }

    private String getBabyDayByBirthday(long birthday, long time2) {
        DateTime startTime = new DateTime(birthday);
        DateTime endTime = new DateTime(time2);
        Period p = new Period(startTime, endTime, PeriodType.yearMonthDay());
        String year = "";
        String month = "";
        String day = "";
        if (p.getYears() != 0) {
            year = p.getYears() + "岁";
        }
        if (p.getMonths() != 0) {
            month = p.getMonths() + "月";
        }
        if (p.getDays() != 0) {
            day = p.getDays() + "天";
        }
        return year + month + day;
    }

    /*注册广播接收器*/
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        /*删除*/
        filter.addAction("delete");
        /*同步*/
        filter.addAction(Config.ACTION_SYNC_TIMELINE_START);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_SUCCESS);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_FAILURE);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_TOKEN_FAILURE);
        /*加载*/
        filter.addAction(Config.ACTION_LOAD_TIMELINE_START);
        filter.addAction(Config.ACTION_LOAD_TIMELINE_SUCCESS);
        filter.addAction(Config.ACTION_LOAD_TIMELINE_FAILURE);
        filter.addAction(Config.ACTION_LOAD_TIMELINE_TOKEN_FAILURE);
        /*照片*/
        filter.addAction(Config.ACTION_SYNC_TIMELINE_PHOTO_START);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_PHOTO_SUCCESS);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_PHOTO_FAILURE);
        /*音频*/
        filter.addAction(Config.ACTION_SYNC_TIMELINE_AUDIO_START);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_AUDIO_SUCCESS);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_AUDIO_FAILURE);
        /*视频*/
        filter.addAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_START);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS);
        filter.addAction(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_FAILURE);
        /*网络连接不可用*/
        filter.addAction(Config.ACTION_NETWORK_UNAVAILABLE);
        mReceiver = new SyncBroadcastReceiver();
        getActivity().registerReceiver(mReceiver, filter);
    }

    /*注销广播接收器*/
    private void unRegisterReceiver() {
        getActivity().unregisterReceiver(mReceiver);
    }

    /*查询剩余时间戳*/
    private TimelineLastServerTime queryLastServerTime(String uuid) {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return null;
        }
        int babyID = loginInfo.getBabyID();
        return DatabaseManager.getInstance(getActivity()).queryLastServerTime(babyID, uuid);
    }

    /*同步完成*/
    private void syncComplete() {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        int babyID = loginInfo.getBabyID();
        int number = Config.QUERY_LENGTH;
        List<Timeline> list = DatabaseManager.getInstance(getActivity()).queryTimeline(babyID, number);
        if (list == null) {
            return;
        }
        mAdapter.clear();
        updateTimeline(list);
        Config.startDownloadTimelineService(getActivity());
    }

    /*停止同步*/
    private void stopSyncUI() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    /*加载更多完成*/
    private void loadComplete(boolean local, long createTS) {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        int babyID = loginInfo.getBabyID();
        int number = Config.QUERY_LENGTH;
        List<Timeline> list = DatabaseManager.getInstance(getActivity()).queryTimeline(babyID, number, createTS);

        for (Timeline timeline : list) {
            Logger.d("类型" + timeline.getType());
        }

        if (list == null || list.size() == 0) {
            if (local) {
                tipShow("没有更早的数据了");
            }
            return;
        }
        updateTimeline(list);
        Config.startDownloadTimelineService(getActivity());
    }

    /*开始加载*/
    private void startLoadUI(RecyclerView recyclerView, int lastPosition) {
        mSlideUpStart = true;
        mProgressBar.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mRecyclerView.getLayoutParams();
        lp.setMargins(0, 0, 0, height);
        recyclerView.setLayoutParams(lp);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        recyclerView.scrollToPosition(lastPosition);
        recyclerView.stopScroll();
    }

    /*停止加载*/
    private void stopLoadUI() {
        mSlideUpStart = false;
        mProgressBar.setVisibility(View.GONE);
        mRecyclerView.setOnTouchListener(null);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mRecyclerView.getLayoutParams();
        lp.setMargins(0, 0, 0, height);
        mRecyclerView.setLayoutParams(lp);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            timeLineBarView.close();
        }
        return false;
    }

    private class SyncBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("delete")) {
                mAdapter.clear();
            }

            if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_START)) {
                // 同步开始
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_SUCCESS)) {
                // 同步成功
                int updateNumber = intent.getIntExtra(Config.ACTION_EXTERNAL_UPDATE_NUMBER, 0);
                if (updateNumber != 0) {
                    Toast.makeText(getActivity(), "同步成功", Toast.LENGTH_SHORT).show();
                    Logger.d("同步数量" + updateNumber);
                    syncComplete();
                } else {
                    Toast.makeText(getActivity(), "已经是最新的数据了", Toast.LENGTH_SHORT).show();
                }
                stopSyncUI();
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_FAILURE)) {
                // 同步失败
                String failureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_MESSAGE);
                Toast.makeText(getActivity(), failureMsg, Toast.LENGTH_SHORT).show();
                stopSyncUI();
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_TOKEN_FAILURE)) {
                // 同步令牌失败
                String tokenFailureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_MESSAGE);
                Toast.makeText(getActivity(), tokenFailureMsg, Toast.LENGTH_SHORT).show();
                stopSyncUI();
            } else if (intent.getAction().equals(Config.ACTION_LOAD_TIMELINE_START)) {
                // 加载开始
            } else if (intent.getAction().equals(Config.ACTION_LOAD_TIMELINE_SUCCESS)) {
                // 加载更多成功
                Log.d("", "加载更多成功");
                long createTS = intent.getLongExtra(Config.ACTION_EXTERNAL_CREATE_TS, 0);
                int updateNumber = intent.getIntExtra(Config.ACTION_EXTERNAL_UPDATE_NUMBER, 0);
                Log.d("createTS", "" + createTS);
                Log.d("updateNumber", "" + updateNumber);

                if (updateNumber != 0) {
                    loadComplete(false, createTS);
                }
                stopLoadUI();
            } else if (intent.getAction().equals(Config.ACTION_LOAD_TIMELINE_FAILURE)) {
                // 加载失败
                String failureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_MESSAGE);
                Toast.makeText(getActivity(), failureMsg, Toast.LENGTH_SHORT).show();
                stopLoadUI();
            } else if (intent.getAction().equals(Config.ACTION_LOAD_TIMELINE_TOKEN_FAILURE)) {
                // 加载令牌失败
                String tokenFailureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_MESSAGE);
                Toast.makeText(getActivity(), tokenFailureMsg, Toast.LENGTH_SHORT).show();
                stopLoadUI();
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_PHOTO_START)) {
                // 图片同步开始
                Log.d("", "图片同步开始");
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_PHOTO_SUCCESS)) {
                // 照片同步成功
                String uuid = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_UUID);
                String url = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_URL);
                String thumbUrl = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_LOCAL_THUMB_URL);
                int number = intent.getIntExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_SUCCESS_NUMBER, 0);
                updateTimeline(uuid, url, thumbUrl);
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_PHOTO_FAILURE)) {
                // 图片同步失败
                String failureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_PHOTO_FAILURE_MESSAGE);
                Log.d("", "图片同步失败" + failureMsg);
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_AUDIO_START)) {
                // 音频同步开始
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_AUDIO_SUCCESS)) {
                // 音频同步成功
                Log.d("", "音频同步成功");
                String uuid = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_UUID);
                String url = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_URL);
                String localUrl = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_SUCCESS_LOCAL_URL);
                updateTimeline(uuid, url, localUrl);
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_AUDIO_FAILURE)) {
                // 音频同步失败
                String failureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_AUDIO_FAILURE_MESSAGE);
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_START)) {
                // 视频截图同步开始
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS)) {
                // 视频截图同步成功
                Log.d("", "视频截图同步成功");
                String uuid = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_UUID);
                String url = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_URL);
                String localUrl = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_SUCCESS_LOCAL_URL);
                updateTimeline(uuid, url, localUrl);
            } else if (intent.getAction().equals(Config.ACTION_SYNC_TIMELINE_VIDEO_SCREENSHOT_FAILURE)) {
                // 视频截图同步失败
                String failureMsg = intent.getStringExtra(Config.ACTION_EXTERNAL_SYNC_TIMELINE_VIDEO_SCREENSHOT_FAILURE_MESSAGE);
            } else if (intent.getAction().equals(Config.ACTION_NETWORK_UNAVAILABLE)) {
                // 网络连接不可用
                stopSyncUI();
                stopLoadUI();
            }
        }
    }

    private class SlideUpListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (mSlideUpStart) {
                return;
            }
            // tipShow(mAdapter.timelineArrayList.get(layoutManager.findFirstVisibleItemPosition()).getDate());
            int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
            int lastPosition = recyclerView.getAdapter().getItemCount() - 1;

            if (lastVisiblePosition != lastPosition || lastVisiblePosition == -1 || lastPosition == -1) {
                return;
            }
            startLoadUI(recyclerView, lastPosition);
            Log.d("uuid", "" + mAdapter.getLastUUID());
            Log.d("createTS", "" + mAdapter.getLastCreateTS());
            TimelineLastServerTime lastServerTime = queryLastServerTime(mAdapter.getLastUUID());
            if (lastServerTime == null) {
                Log.d("", "本地");
                loadComplete(true, mAdapter.getLastCreateTS());
                stopLoadUI();
            } else {
                Log.d("", "服务器");
                Config.startLoadTimelineService(getActivity());
            }
        }
    }

}
